#!/bin/bash

# 跨平台动态库编译脚本
# 支持: macOS, Linux, Windows, Android, iOS

set -e

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🌍 跨平台动态库编译脚本"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# 检查Go环境
if ! command -v go &> /dev/null; then
    echo "❌ Go未安装或不在PATH中"
    exit 1
fi

echo "✅ Go版本: $(go version)"
echo ""

# 创建输出目录
OUTPUT_DIR="../assets/libs"
mkdir -p "$OUTPUT_DIR"

# 编译标志
BUILD_FLAGS="-ldflags=-s -ldflags=-w"  # 减小文件大小
if [[ "$1" == "debug" ]]; then
    BUILD_FLAGS=""
    echo "🐛 调试模式构建"
else
    echo "🚀 发布模式构建"
fi
echo ""

# 构建计数器
SUCCESS_COUNT=0
FAIL_COUNT=0
TOTAL_COUNT=0

# 构建函数
build_library() {
    local GOOS=$1
    local GOARCH=$2
    local OUTPUT_FILE=$3
    local DESCRIPTION=$4
    
    TOTAL_COUNT=$((TOTAL_COUNT + 1))
    
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "🔨 编译 $DESCRIPTION"
    echo "   OS: $GOOS, ARCH: $GOARCH"
    echo "   输出: $OUTPUT_FILE"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    # 清理之前的构建
    if [[ -f "$OUTPUT_FILE" ]]; then
        rm -f "$OUTPUT_FILE"
        rm -f "${OUTPUT_FILE%.*}.h"
    fi
    
    # 设置环境变量
    export GOOS=$GOOS
    export GOARCH=$GOARCH
    export CGO_ENABLED=1
    
    # 设置Android特定的环境
    if [[ "$GOOS" == "android" ]]; then
        # 检查NDK环境
        if [[ -z "$ANDROID_NDK_HOME" ]]; then
            if [[ -d "$HOME/Library/Android/sdk/ndk" ]]; then
                # macOS默认NDK路径
                NDK_VERSION=$(ls "$HOME/Library/Android/sdk/ndk" | sort -V | tail -n 1)
                export ANDROID_NDK_HOME="$HOME/Library/Android/sdk/ndk/$NDK_VERSION"
            elif [[ -d "$ANDROID_HOME/ndk" ]]; then
                NDK_VERSION=$(ls "$ANDROID_HOME/ndk" | sort -V | tail -n 1)
                export ANDROID_NDK_HOME="$ANDROID_HOME/ndk/$NDK_VERSION"
            fi
        fi
        
        if [[ -z "$ANDROID_NDK_HOME" ]]; then
            echo "⚠️  未找到Android NDK，跳过Android编译"
            echo "   请设置 ANDROID_NDK_HOME 环境变量"
            FAIL_COUNT=$((FAIL_COUNT + 1))
            return 1
        fi
        
        # 设置Android交叉编译工具链
        case "$GOARCH" in
            arm)
                export CC="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/darwin-x86_64/bin/armv7a-linux-androideabi21-clang"
                ;;
            arm64)
                export CC="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/darwin-x86_64/bin/aarch64-linux-android21-clang"
                ;;
            386)
                export CC="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/darwin-x86_64/bin/i686-linux-android21-clang"
                ;;
            amd64)
                export CC="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/darwin-x86_64/bin/x86_64-linux-android21-clang"
                ;;
        esac
    fi
    
    # 开始编译
    if go build -buildmode=c-shared $BUILD_FLAGS -o "$OUTPUT_FILE" . 2>&1; then
        if [[ -f "$OUTPUT_FILE" ]]; then
            FILE_SIZE=$(ls -lh "$OUTPUT_FILE" | awk '{print $5}')
            echo "✅ 编译成功! 文件大小: $FILE_SIZE"
            SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
            
            # macOS需要签名
            if [[ "$GOOS" == "darwin" ]] && command -v codesign &> /dev/null; then
                echo "🔐 执行代码签名..."
                if codesign --force --sign "-" --timestamp "$OUTPUT_FILE" 2>/dev/null; then
                    echo "✅ 签名成功"
                else
                    echo "⚠️  签名失败，但库仍可使用"
                fi
            fi
            
            return 0
        else
            echo "❌ 编译失败: 输出文件未生成"
            FAIL_COUNT=$((FAIL_COUNT + 1))
            return 1
        fi
    else
        echo "❌ 编译失败"
        FAIL_COUNT=$((FAIL_COUNT + 1))
        return 1
    fi
}

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📦 开始跨平台编译"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# 1. macOS (Darwin)
echo "🍎 编译 macOS 版本..."
build_library "darwin" "arm64" "$OUTPUT_DIR/libsimple_tunnel_darwin_arm64.dylib" "macOS ARM64"
build_library "darwin" "amd64" "$OUTPUT_DIR/libsimple_tunnel_darwin_amd64.dylib" "macOS x86_64"
echo ""

# 2. Linux
echo "🐧 编译 Linux 版本..."
# 检测当前操作系统
CURRENT_OS=$(uname -s)
if [[ "$CURRENT_OS" == "Linux" ]]; then
    # 在Linux系统上可以直接编译
    build_library "linux" "amd64" "$OUTPUT_DIR/libsimple_tunnel_linux_amd64.so" "Linux x86_64"
    build_library "linux" "arm64" "$OUTPUT_DIR/libsimple_tunnel_linux_arm64.so" "Linux ARM64"
else
    # 在非Linux系统上，跳过Linux编译（CGO交叉编译有限制）
    echo "⚠️  在 $CURRENT_OS 上跳过Linux编译（CGO交叉编译限制）"
    echo "   提示: 如需编译Linux版本，请在Linux系统上运行此脚本"
    echo "   或使用Docker: docker run --rm -v \$(pwd):/work golang:latest bash /work/build_cross_platform.sh"
    FAIL_COUNT=$((FAIL_COUNT + 2))
    TOTAL_COUNT=$((TOTAL_COUNT + 2))
fi
echo ""

# 3. Windows
echo "🪟 编译 Windows 版本..."
if [[ "$CURRENT_OS" == "MINGW"* ]] || [[ "$CURRENT_OS" == "MSYS"* ]] || [[ "$CURRENT_OS" == "CYGWIN"* ]]; then
    # 在Windows系统上可以直接编译
    build_library "windows" "amd64" "$OUTPUT_DIR/simple_tunnel_windows_amd64.dll" "Windows x86_64"
else
    # 在非Windows系统上，跳过Windows编译（CGO交叉编译有限制）
    echo "⚠️  在 $CURRENT_OS 上跳过Windows编译（CGO交叉编译限制）"
    echo "   提示: 如需编译Windows版本，请在Windows系统上运行此脚本"
    echo "   或使用MinGW交叉编译工具链"
    FAIL_COUNT=$((FAIL_COUNT + 1))
    TOTAL_COUNT=$((TOTAL_COUNT + 1))
fi
echo ""

# 4. Android
echo "🤖 编译 Android 版本..."
build_library "android" "arm" "$OUTPUT_DIR/libsimple_tunnel_android_arm.so" "Android ARM"
build_library "android" "arm64" "$OUTPUT_DIR/libsimple_tunnel_android_arm64.so" "Android ARM64"
build_library "android" "386" "$OUTPUT_DIR/libsimple_tunnel_android_x86.so" "Android x86"
build_library "android" "amd64" "$OUTPUT_DIR/libsimple_tunnel_android_x86_64.so" "Android x86_64"
echo ""

# 5. iOS (需要特殊处理)
echo "📱 编译 iOS 版本..."
if command -v xcrun &> /dev/null; then
    # iOS真机 (ARM64)
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "🔨 编译 iOS ARM64 (真机)"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    export GOOS=ios
    export GOARCH=arm64
    export CGO_ENABLED=1
    export CGO_CFLAGS="-fembed-bitcode"
    export CC="$(xcrun --sdk iphoneos --find clang)"
    export CGO_LDFLAGS="-isysroot $(xcrun --sdk iphoneos --show-sdk-path)"
    
    OUTPUT_FILE="$OUTPUT_DIR/libsimple_tunnel_ios_arm64.a"
    
    if go build -buildmode=c-archive $BUILD_FLAGS -o "$OUTPUT_FILE" . 2>&1; then
        if [[ -f "$OUTPUT_FILE" ]]; then
            FILE_SIZE=$(ls -lh "$OUTPUT_FILE" | awk '{print $5}')
            echo "✅ iOS ARM64编译成功! 文件大小: $FILE_SIZE"
            SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
        fi
    else
        echo "❌ iOS ARM64编译失败"
        FAIL_COUNT=$((FAIL_COUNT + 1))
    fi
    
    TOTAL_COUNT=$((TOTAL_COUNT + 1))
    echo ""
    
    # iOS模拟器 (x86_64 + ARM64)
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "🔨 编译 iOS Simulator (x86_64 + ARM64)"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    # x86_64
    export GOOS=darwin
    export GOARCH=amd64
    export CGO_ENABLED=1
    export CC="$(xcrun --sdk iphonesimulator --find clang)"
    export CGO_LDFLAGS="-isysroot $(xcrun --sdk iphonesimulator --show-sdk-path)"
    
    OUTPUT_FILE_X86="$OUTPUT_DIR/libsimple_tunnel_ios_sim_x86_64.a"
    
    if go build -buildmode=c-archive $BUILD_FLAGS -o "$OUTPUT_FILE_X86" . 2>&1; then
        if [[ -f "$OUTPUT_FILE_X86" ]]; then
            FILE_SIZE=$(ls -lh "$OUTPUT_FILE_X86" | awk '{print $5}')
            echo "✅ iOS Simulator x86_64编译成功! 文件大小: $FILE_SIZE"
            SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
        fi
    else
        echo "❌ iOS Simulator x86_64编译失败"
        FAIL_COUNT=$((FAIL_COUNT + 1))
    fi
    
    TOTAL_COUNT=$((TOTAL_COUNT + 1))
    echo ""
    
    # ARM64 (Apple Silicon Mac)
    export GOARCH=arm64
    OUTPUT_FILE_ARM64="$OUTPUT_DIR/libsimple_tunnel_ios_sim_arm64.a"
    
    if go build -buildmode=c-archive $BUILD_FLAGS -o "$OUTPUT_FILE_ARM64" . 2>&1; then
        if [[ -f "$OUTPUT_FILE_ARM64" ]]; then
            FILE_SIZE=$(ls -lh "$OUTPUT_FILE_ARM64" | awk '{print $5}')
            echo "✅ iOS Simulator ARM64编译成功! 文件大小: $FILE_SIZE"
            SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
        fi
    else
        echo "❌ iOS Simulator ARM64编译失败"
        FAIL_COUNT=$((FAIL_COUNT + 1))
    fi
    
    TOTAL_COUNT=$((TOTAL_COUNT + 1))
    echo ""
    
else
    echo "⚠️  Xcode命令行工具未安装，跳过iOS编译"
    echo "   安装方法: xcode-select --install"
    FAIL_COUNT=$((FAIL_COUNT + 3))
    TOTAL_COUNT=$((TOTAL_COUNT + 3))
fi

# 编译总结
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📊 编译统计"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "总计: $TOTAL_COUNT 个目标"
echo "✅ 成功: $SUCCESS_COUNT"
echo "❌ 失败: $FAIL_COUNT"
echo ""

# 列出生成的文件
if [[ $SUCCESS_COUNT -gt 0 ]]; then
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "📁 生成的文件"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    ls -lh "$OUTPUT_DIR" | grep -E "\.(dylib|so|dll|a)$" | awk '{printf "   %s  %s\n", $5, $9}'
    echo ""
fi

# 生成Flutter平台配置文件
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📝 生成Flutter平台配置"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

cat > "$OUTPUT_DIR/README.md" << 'EOL'
# 跨平台动态库说明

## 文件命名规范

```
libsimple_tunnel_<platform>_<arch>.<ext>
```

## 平台对应关系

### macOS (Darwin)
- `libsimple_tunnel_darwin_arm64.dylib` - Apple Silicon (M1/M2/M3)
- `libsimple_tunnel_darwin_amd64.dylib` - Intel Mac

### Linux
- `libsimple_tunnel_linux_amd64.so` - x86_64
- `libsimple_tunnel_linux_arm64.so` - ARM64

### Windows
- `simple_tunnel_windows_amd64.dll` - x86_64

### Android
- `libsimple_tunnel_android_arm.so` - ARMv7
- `libsimple_tunnel_android_arm64.so` - ARM64
- `libsimple_tunnel_android_x86.so` - x86 (模拟器)
- `libsimple_tunnel_android_x86_64.so` - x86_64 (模拟器)

### iOS
- `libsimple_tunnel_ios_arm64.a` - iPhone/iPad真机
- `libsimple_tunnel_ios_sim_x86_64.a` - 模拟器 (Intel Mac)
- `libsimple_tunnel_ios_sim_arm64.a` - 模拟器 (Apple Silicon)

## Flutter集成

在Flutter中使用时，会自动根据平台选择对应的库文件。

详见: `lib/native/tunnel_bridge.dart`
EOL

echo "✅ 配置文件已生成: $OUTPUT_DIR/README.md"
echo ""

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [[ $FAIL_COUNT -eq 0 ]]; then
    echo "🎉 全部编译成功！"
else
    echo "⚠️  部分编译失败，请查看上面的详细信息"
fi
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "🚀 下一步:"
echo "   1. 检查生成的库文件: $OUTPUT_DIR"
echo "   2. 在Flutter中测试各平台的动态加载"
echo "   3. Android需要将.so文件复制到对应的jniLibs目录"
echo "   4. iOS需要在Xcode中配置静态库链接"
echo ""
echo "✨ 完成！"

